<template>
  <view class="course-publish-page">
    <view class="form-container">
      <!-- 课程封面/视频上传 -->
      <view class="form-section">
        <view class="section-title required">课程封面/视频</view>
        <view class="upload-section">
          <view class="upload-item" v-if="formData.coverImage" @click="previewImage">
            <image class="uploaded-image" :src="formData.coverImage" mode="aspectFill" />
            <view class="delete-btn" @click.stop="deleteCover">
              <text class="iconfont-v2 icon-close"></text>
            </view>
          </view>
          <view class="upload-placeholder" v-else @click="uploadCover">
            <text class="iconfont icon-icon25201 upload-icon"></text>
            <text class="upload-text">上传封面/视频</text>
          </view>
        </view>
      </view>

      <!-- 课程标题 -->
      <view class="form-section">
        <view class="section-title required">课程标题</view>
        <input 
          class="form-input" 
          type="text" 
          placeholder="请输入课程标题" 
          v-model="formData.title"
          maxlength="50"
        />
      </view>

      <!-- 课程分类 -->
      <view class="form-section">
        <view class="section-title required">课程分类</view>
        <view class="picker-wrapper" @click="openCategoryPicker">
          <input 
            class="form-input" 
            type="text" 
            placeholder="请选择课程分类" 
            v-model="categoryName"
            readonly
            disabled
          />
          <text class="iconfont icon-ic_rightarrow picker-arrow"></text>
        </view>
      </view>

      <!-- 课程简介 -->
      <view class="form-section">
        <view class="section-title required">课程简介</view>
        <textarea 
          class="form-textarea" 
          placeholder="请输入课程简介，介绍课程内容、适合人群等"
          v-model="formData.introduction"
          maxlength="500"
        />
        <view class="char-count">{{ formData.introduction.length }}/500</view>
      </view>

      <!-- 课程价格 -->
      <view class="form-section">
        <view class="section-title required">课程价格</view>
        <view class="price-row">
          <input 
            class="form-input price-input" 
            type="digit" 
            placeholder="0.00" 
            v-model="formData.price"
          />
          <text class="price-unit">元</text>
        </view>
        <view class="price-tip">设置为0表示免费课程</view>
      </view>

      <!-- 课程模块列表 -->
      <view class="form-section">
        <view class="section-header">
          <view class="section-title required">课程模块</view>
          <view class="add-module-btn" @click="addModule">
            <text class="iconfont-v2 icon-jia add-icon"></text>
            <text>添加模块</text>
          </view>
        </view>
        
        <view class="module-list">
          <view 
            class="module-item" 
            v-for="(module, index) in formData.modules" 
            :key="index"
          >
            <view class="module-header">
              <view class="module-number">{{ String(index + 1).padStart(2, "0") }}</view>
              <view class="module-actions">
                <view class="action-icon" @click="editModule(index)">
                  <text class="iconfont-v2 icon-bianji"></text>
                </view>
                <view class="action-icon" @click="deleteModule(index)">
                  <text class="iconfont-v2 icon-shanchu"></text>
                </view>
              </view>
            </view>
            <view class="module-content">
              <text class="module-title">{{ module.title || '未设置标题' }}</text>
              <view class="module-info">
                <text class="module-duration">{{ module.duration || '未设置时长' }}</text>
                <text v-if="module.video" class="module-video">已上传视频</text>
              </view>
            </view>
          </view>
          
          <view v-if="formData.modules.length === 0" class="empty-modules">
            <text class="empty-text">暂无课程模块，请添加</text>
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-section">
        <button class="submit-btn" @click="submitForm">发布课程</button>
      </view>
    </view>

    <!-- 课程分类选择器 -->
    <u-picker
      :show="showCategoryPicker"
      ref="categoryPicker"
      :columns="[categoryList]"
      keyName="name"
      @confirm="confirmCategory"
      @cancel="showCategoryPicker = false"
    ></u-picker>

    <!-- 模块编辑弹窗 -->
    <u-popup 
      :show="showModuleModal" 
      mode="bottom" 
      :round="20"
      height="auto"
      :z-index="10080"
      @close="closeModuleModal"
    >
      <view class="module-modal">
        <view class="modal-header">
          <text class="modal-title">{{ editingModuleIndex >= 0 ? '编辑模块' : '添加模块' }}</text>
          <view class="modal-close" @click="closeModuleModal">
            <text class="iconfont-v2 icon-close"></text>
          </view>
        </view>
        <view class="modal-content">
          <view class="modal-section">
            <view class="modal-label required">模块标题</view>
            <input 
              class="modal-input" 
              type="text" 
              placeholder="请输入模块标题" 
              v-model="currentModule.title"
            />
          </view>
          <view class="modal-section">
            <view class="modal-label required">视频时长</view>
            <view class="duration-inputs">
              <input 
                class="modal-input duration-input" 
                type="number" 
                placeholder="小时" 
                v-model.number="currentModule.hours"
              />
              <text class="duration-separator">:</text>
              <input 
                class="modal-input duration-input" 
                type="number" 
                placeholder="分钟" 
                v-model.number="currentModule.minutes"
              />
            </view>
          </view>
          <view class="modal-section">
            <view class="modal-label">上传视频</view>
            <view class="video-upload" @click="uploadVideo">
              <text v-if="currentModule.video" class="video-name">{{ currentModule.videoName || '已上传视频' }}</text>
              <text v-else class="upload-video-text">
                <text class="iconfont icon-icon25201"></text>
                上传视频
              </text>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <button class="modal-btn cancel-btn" @click="closeModuleModal">取消</button>
          <button class="modal-btn confirm-btn" @click="saveModule">保存</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        coverImage: '',
        title: '',
        categoryId: 0,
        introduction: '',
        price: '0.00',
        modules: []
      },
      categoryName: '',
      categoryList: [
        { id: 1, name: '语言培训' },
        { id: 2, name: '技能培训' },
        { id: 3, name: '艺术培训' },
        { id: 4, name: '职业培训' },
        { id: 5, name: '其他' }
      ],
      showCategoryPicker: false,
      showModuleModal: false,
      editingModuleIndex: -1,
      currentModule: {
        title: '',
        hours: 0,
        minutes: 0,
        video: '',
        videoName: '',
        duration: ''
      }
    }
  },
  methods: {
    // 上传封面
    uploadCover() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 这里应该调用上传接口
          this.formData.coverImage = res.tempFilePaths[0];
        }
      });
    },
    // 预览封面
    previewImage() {
      uni.previewImage({
        urls: [this.formData.coverImage],
        current: this.formData.coverImage
      });
    },
    // 删除封面
    deleteCover() {
      this.formData.coverImage = '';
    },
    // 打开分类选择器
    openCategoryPicker() {
      this.showCategoryPicker = true;
    },
    // 确认分类
    confirmCategory(e) {
      const idx = (e.indexs && e.indexs[0]) || 0;
      const item = this.categoryList[idx];
      if (item) {
        this.formData.categoryId = item.id;
        this.categoryName = item.name;
      }
      this.showCategoryPicker = false;
    },
    // 添加模块
    addModule() {
      console.log('addModule called');
      this.editingModuleIndex = -1;
      this.currentModule = {
        title: '',
        hours: 0,
        minutes: 0,
        video: '',
        videoName: '',
        duration: ''
      };
      this.showModuleModal = true;
      console.log('showModuleModal set to:', this.showModuleModal);
      // 使用 $nextTick 确保 DOM 更新
      this.$nextTick(() => {
        console.log('After nextTick, showModuleModal:', this.showModuleModal);
      });
    },
    // 编辑模块
    editModule(index) {
      this.editingModuleIndex = index;
      const module = this.formData.modules[index];
      this.currentModule = {
        title: module.title || '',
        hours: module.hours || 0,
        minutes: module.minutes || 0,
        video: module.video || '',
        videoName: module.videoName || '',
        duration: module.duration || ''
      };
      this.showModuleModal = true;
    },
    // 删除模块
    deleteModule(index) {
      uni.showModal({
        title: '提示',
        content: '确定要删除这个模块吗？',
        success: (res) => {
          if (res.confirm) {
            this.formData.modules.splice(index, 1);
          }
        }
      });
    },
    // 上传视频
    uploadVideo() {
      uni.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 3600,
        camera: 'back',
        success: (res) => {
          // 这里应该调用上传接口
          this.currentModule.video = res.tempFilePath;
          this.currentModule.videoName = res.tempFilePath.split('/').pop();
        }
      });
    },
    // 保存模块
    saveModule() {
      if (!this.currentModule.title) {
        uni.showToast({
          title: '请输入模块标题',
          icon: 'none'
        });
        return;
      }
      
      // 计算时长
      const hours = this.currentModule.hours || 0;
      const minutes = this.currentModule.minutes || 0;
      let durationText = '';
      if (hours > 0 && minutes > 0) {
        durationText = `${hours}小时${minutes}分钟`;
      } else if (hours > 0) {
        durationText = `${hours}小时`;
      } else if (minutes > 0) {
        durationText = `${minutes}分钟`;
      } else {
        durationText = '0分钟';
      }
      
      const moduleData = {
        title: this.currentModule.title,
        hours: hours,
        minutes: minutes,
        duration: durationText,
        video: this.currentModule.video,
        videoName: this.currentModule.videoName
      };
      
      if (this.editingModuleIndex >= 0) {
        // 编辑模式
        this.$set(this.formData.modules, this.editingModuleIndex, moduleData);
      } else {
        // 添加模式
        this.formData.modules.push(moduleData);
      }
      
      this.closeModuleModal();
    },
    // 关闭模块弹窗
    closeModuleModal() {
      this.showModuleModal = false;
      this.editingModuleIndex = -1;
      this.currentModule = {
        title: '',
        hours: 0,
        minutes: 0,
        video: '',
        videoName: '',
        duration: ''
      };
    },
    // 提交表单
    submitForm() {
      // 验证表单
      if (!this.formData.coverImage) {
        uni.showToast({
          title: '请上传课程封面',
          icon: 'none'
        });
        return;
      }
      
      if (!this.formData.title) {
        uni.showToast({
          title: '请输入课程标题',
          icon: 'none'
        });
        return;
      }
      
      if (!this.formData.categoryId) {
        uni.showToast({
          title: '请选择课程分类',
          icon: 'none'
        });
        return;
      }
      
      if (!this.formData.introduction) {
        uni.showToast({
          title: '请输入课程简介',
          icon: 'none'
        });
        return;
      }
      
      if (this.formData.modules.length === 0) {
        uni.showToast({
          title: '请至少添加一个课程模块',
          icon: 'none'
        });
        return;
      }
      
      // 这里应该调用提交接口
      console.log('提交课程数据:', this.formData);
      uni.showToast({
        title: '发布成功',
        icon: 'success'
      });
      
      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  }
}
</script>

<style lang="scss" scoped>
.course-publish-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 40rpx;
}

.form-container {
  padding: 20rpx;
}

.form-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
  
  &.required::before {
    content: '* ';
    color: #ED6567;
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.add-module-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  color: #ED6567;
  font-size: 28rpx;
  
  .add-icon {
    font-size: 32rpx;
  }
}

.upload-section {
  .upload-item {
    position: relative;
    width: 100%;
    height: 400rpx;
    border-radius: 12rpx;
    overflow: hidden;
    
    .uploaded-image {
      width: 100%;
      height: 100%;
    }
    
    .delete-btn {
      position: absolute;
      top: 10rpx;
      right: 10rpx;
      width: 60rpx;
      height: 60rpx;
      background: rgba(0, 0, 0, 0.6);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .iconfont-v2 {
        color: white;
        font-size: 32rpx;
      }
    }
  }
  
  .upload-placeholder {
    width: 100%;
    height: 400rpx;
    border: 2rpx dashed #ddd;
    border-radius: 12rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 16rpx;
    background: #fafafa;
    
    .upload-icon {
      font-size: 80rpx;
      color: #999;
    }
    
    .upload-text {
      font-size: 28rpx;
      color: #999;
    }
  }
}

.form-input {
  width: 100%;
  height: 88rpx;
  padding: 0 24rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
  border: 2rpx solid transparent;
  
  &:focus {
    border-color: #ED6567;
    background: white;
  }
}

.picker-wrapper {
  position: relative;
  
  .picker-arrow {
    position: absolute;
    right: 24rpx;
    top: 50%;
    transform: translateY(-50%);
    font-size: 28rpx;
    color: #999;
  }
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
  border: 2rpx solid transparent;
  
  &:focus {
    border-color: #ED6567;
    background: white;
  }
}

.char-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 12rpx;
}

.price-row {
  display: flex;
  align-items: center;
  gap: 16rpx;
  
  .price-input {
    flex: 1;
  }
  
  .price-unit {
    font-size: 28rpx;
    color: #333;
  }
}

.price-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 12rpx;
}

.module-list {
  .module-item {
    padding: 24rpx;
    background: #f8f9fa;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .module-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16rpx;
      
      .module-number {
        width: 50rpx;
        height: 50rpx;
        background: #ED6567;
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        font-weight: 600;
      }
      
      .module-actions {
        display: flex;
        gap: 24rpx;
        
        .action-icon {
          font-size: 32rpx;
          color: #666;
        }
      }
    }
    
    .module-content {
      .module-title {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-bottom: 12rpx;
        display: block;
      }
      
      .module-info {
        display: flex;
        gap: 24rpx;
        font-size: 24rpx;
        color: #999;
        
        .module-video {
          color: #ED6567;
        }
      }
    }
  }
  
  .empty-modules {
    padding: 60rpx 0;
    text-align: center;
    
    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }
}

.submit-section {
  padding: 40rpx 20rpx;
  
  .submit-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: #ED6567;
    color: white;
    border: none;
    border-radius: 50rpx;
    font-size: 32rpx;
    font-weight: 600;
  }
}

// 模块编辑弹窗
.module-modal {
  background: white;
  border-radius: 20rpx 20rpx 0 0;
  padding: 40rpx;
  
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;
    
    .modal-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
    
    .modal-close {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .iconfont-v2 {
        font-size: 32rpx;
        color: #999;
      }
    }
  }
  
  .modal-content {
    .modal-section {
      margin-bottom: 40rpx;
      
      .modal-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 16rpx;
        
        &.required::before {
          content: '* ';
          color: #ED6567;
        }
      }
      
      .modal-input {
        width: 100%;
        height: 88rpx;
        padding: 0 24rpx;
        background: #f8f9fa;
        border-radius: 12rpx;
        font-size: 28rpx;
        color: #333;
      }
      
      .duration-inputs {
        display: flex;
        align-items: center;
        gap: 16rpx;
        
        .duration-input {
          flex: 1;
        }
        
        .duration-separator {
          font-size: 32rpx;
          color: #333;
        }
      }
      
      .video-upload {
        padding: 24rpx;
        background: #f8f9fa;
        border-radius: 12rpx;
        text-align: center;
        
        .video-name {
          font-size: 28rpx;
          color: #333;
        }
        
        .upload-video-text {
          font-size: 28rpx;
          color: #999;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 12rpx;
          
          .iconfont {
            font-size: 32rpx;
          }
        }
      }
    }
  }
  
  .modal-footer {
    display: flex;
    gap: 20rpx;
    margin-top: 40rpx;
    
    .modal-btn {
      flex: 1;
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 50rpx;
      font-size: 32rpx;
      border: none;
      
      &.cancel-btn {
        background: #f0f0f0;
        color: #666;
      }
      
      &.confirm-btn {
        background: #ED6567;
        color: white;
      }
    }
  }
}
</style>

